﻿using Pay.Core;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pay.Distribution {
    /// <summary>
	/// 错误日志
	/// </summary>
	public class HandleExceptionAttribute : HandleErrorAttribute, IExceptionFilter {
        public override void OnException(ExceptionContext filterContext) {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");
            if (filterContext.IsChildAction)
                return;
            if (filterContext.ExceptionHandled)
                return;
            var ex = filterContext.Exception.GetBaseException() ?? new Exception("No further infomation exists.");
            if (!ExceptionType.IsInstanceOfType(ex))
                return;

            var log = IocHelper.Get<ILogHelper>("ui_error");
            if (!(ex is ServerErrorException || ex is DataErrorException || filterContext.HttpContext.Response.StatusCode == 401)) {
                string message = string.Format("消息类型：{0}\r\n消息内容：{1}\r\n引发异常的方法：{2}\r\n引发异常源：{3}"
                                , filterContext.Exception.GetType().Name
                                , filterContext.Exception.Message
                                 , filterContext.Exception.TargetSite
                                 , filterContext.Exception.Source + filterContext.Exception.StackTrace);
                log.Error(message);
            }

            if (filterContext.HttpContext.Request.IsAjaxRequest()) {
                if (ex is ServerErrorException) {
                    var serverEx = ex as ServerErrorException;
                    if (serverEx.ErrorCode > 0)
                        filterContext.Result = new JsonNetResult(new ResultMessage<object>(serverEx.ErrorCode, ex.Message));
                    else
                        filterContext.Result = new JsonNetResult(new ResultMessage<object>(filterContext.HttpContext.Response.StatusCode, ex.Message));
                } else
                    filterContext.Result = new JsonNetResult(new ResultMessage<object>(filterContext.HttpContext.Response.StatusCode, ex.Message));
            } else {
                HandleErrorInfo data = new HandleErrorInfo(ex, (string)filterContext.RouteData.Values["controller"], (string)filterContext.RouteData.Values["action"]);
                filterContext.Controller.ViewData.Model = data;
                filterContext.Result = new ViewResult { ViewName = "Error", ViewData = filterContext.Controller.ViewData };
            }
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}